#define  _CRT_SECURE_NO_WARNINGS  1
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> vv;
        sort(nums.begin(), nums.end());
        int n = nums.size();
        for (int i = 0; i < n;)
        {
            int a = nums[i];
            for (int j = i + 1; j < n;)
            {
                int b = nums[j];
                int left = j + 1, right = n - 1;
                long long add = (long long)target - a - b;
                while (left < right)
                {
                    int sum = nums[left] + nums[right];
                    if (sum > add) right--;
                    else if (sum < add) left++;
                    else
                    {
                        vv.push_back({ nums[left],nums[right],a,b });
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]) left++;
                        while (left < right && nums[right] == nums[right + 1]) right--;
                    }
                }
                j++;
                while (j < n && nums[j] == nums[j - 1]) j++;
            }
            i++;
            while (i < n && nums[i] == nums[i - 1]) i++;
        }
        return vv;
    }
};